import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes, CategoryItem, SubCategory, TopCategory } from '@/types/data'
import { topCategory } from '../constants'

// interface CategoryItem {
//   id: string
//   name: string
//   picture: string
// }

// interface ApiRes<T> {
//   code: string
//   msg: string
//   result: T[]
// }

const defaultCatgory = topCategory.map(item => ({ name: item }))

// defineStore 返回的是一个函数
export default defineStore('category', {
  state() {
    return {
      list: defaultCatgory as CategoryItem[],
      topCategory: {} as TopCategory,
      subCategory: {} as SubCategory
    }
  },
  actions: {
    async getAllCategory() {
      const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
      this.list.forEach(item => item.open = false)
      // console.log(res.data.result)
      this.list = res.data.result
    },
    show(id: string) {
      const item = this.list.find(item => item.id === id)
      item!.open = true
    },
    hide(id: string) {
      const item = this.list.find(item => item.id === id)
      item!.open = false
    },
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategory>>('/category', {
        params: {
          id
        }
      })
      this.topCategory = res.data.result
    },
    async getSubCategory(id: string) {
      const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
        params: {
          id
        }
      })
      this.subCategory = res.data.result
    },
    resetSubCategory() {
      this.subCategory = {} as SubCategory
    },
    resetTopCategory() {
      this.topCategory = {} as TopCategory
    }
  }
})
